package com.ksd.modules.upload.controller;

import com.alibaba.fastjson.JSONObject;
import com.ksd.common.controller.BaseController;
import com.ksd.modules.upload.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
public class OssController extends BaseController {

    @Autowired
    private FileService fileService;

    //  社区图片上传至阿里云，feign无法远程调用，故集成到这里
    @PostMapping("/oss/upload/file")
    public JSONObject fileUploadComment(@RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        String path = request.getParameter("path");
        String oldName = request.getParameter("oldName");
        //给editormd进行回调
        JSONObject res = new JSONObject();
        // 上传图片文件到oss
        String url = fileService.upload(file, path,oldName);
        res.put("url",url);
        res.put("filename",file.getName());
        res.put("filesize",file.getSize());
        res.put("filetype",file.getContentType());
        res.put("success", "1");
        res.put("message", "upload success!");
        return res;
    }


    //  用户主页文件上传至阿里云
    @PostMapping("/oss/upload/mdeditor")
    public JSONObject fileUploadUserhome(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        // 上传图片文件到oss
        String path = request.getParameter("path");
        String oldName = request.getParameter("oldName");
        //给editormd进行回调
        JSONObject res = new JSONObject();
        // 上传图片文件到oss
        String url = fileService.upload(file, path,oldName);
        //给editormd进行回调
        res.put("url",url);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;
    }
}
